/* eslint-disable */
import { saveAs } from 'file-saver';
import * as ExcelJS from 'exceljs';
import * as XLSX from 'xlsx';

function generateArray(table) {
  var out = [];
  var rows = table.querySelectorAll('tr');
  var ranges = [];
  for (var R = 0; R < rows.length; ++R) {
    var outRow = [];
    var row = rows[R];
    var columns = row.querySelectorAll('td');
    for (var C = 0; C < columns.length; ++C) {
      var cell = columns[C];
      var colspan = cell.getAttribute('colspan');
      var rowspan = cell.getAttribute('rowspan');
      var cellValue = cell.innerText;
      if (cellValue !== '' && cellValue == +cellValue) cellValue = +cellValue;

      //Skip ranges
      ranges.forEach(function (range) {
        if (
          R >= range.s.r &&
          R <= range.e.r &&
          outRow.length >= range.s.c &&
          outRow.length <= range.e.c
        ) {
          for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
        }
      });

      //Handle Row Span
      if (rowspan || colspan) {
        rowspan = rowspan || 1;
        colspan = colspan || 1;
        ranges.push({
          s: {
            r: R,
            c: outRow.length,
          },
          e: {
            r: R + rowspan - 1,
            c: outRow.length + colspan - 1,
          },
        });
      }

      //Handle Value
      outRow.push(cellValue !== '' ? cellValue : null);

      //Handle Colspan
      if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
    }
    out.push(outRow);
  }
  return [out, ranges];
}

function datenum(v, date1904) {
  if (date1904) v += 1462;
  var epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
  var ws = {};
  var range = {
    s: {
      c: 10000000,
      r: 10000000,
    },
    e: {
      c: 0,
      r: 0,
    },
  };
  for (var R = 0; R != data.length; ++R) {
    for (var C = 0; C != data[R].length; ++C) {
      if (range.s.r > R) range.s.r = R;
      if (range.s.c > C) range.s.c = C;
      if (range.e.r < R) range.e.r = R;
      if (range.e.c < C) range.e.c = C;
      var cell = {
        v: data[R][C],
      };
      if (cell.v == null) continue;
      var cell_ref = XLSX.utils.encode_cell({
        c: C,
        r: R,
      });

      if (typeof cell.v === 'number') cell.t = 'n';
      else if (typeof cell.v === 'boolean') cell.t = 'b';
      else if (cell.v instanceof Date) {
        cell.t = 'n';
        cell.z = XLSX.SSF._table[14];
        cell.v = datenum(cell.v);
      } else cell.t = 's';

      ws[cell_ref] = cell;
    }
  }
  if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
  return ws;
}

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  this.Sheets = {};
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
  return buf;
}

export function export_table_to_excel(id) {
  var theTable = document.getElementById(id);
  var oo = generateArray(theTable);
  var ranges = oo[1];

  /* original data */
  var data = oo[0];
  var ws_name = 'SheetJS';

  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  /* add ranges to worksheet */
  // ws['!cols'] = ['apple', 'banan'];
  ws['!merges'] = ranges;

  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;

  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary',
  });

  saveAs(
    new Blob([s2ab(wbout)], {
      type: 'application/octet-stream',
    }),
    'test.xlsx',
  );
}

export function export_json_to_excel(
  {
    multiHeader = [],
    header,
    data,
    filename,
    merges = [],
    autoWidth = true,
    bookType = 'xlsx',
  } = {},
  mengXiData = {},
) {
  /* original data */
  filename = filename || 'excel-list';
  data = [...data];
  data.unshift(header);

  for (let i = multiHeader.length - 1; i > -1; i--) {
    data.unshift(multiHeader[i]);
  }

  var ws_name = 'SheetJS';
  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  if (merges.length > 0) {
    if (!ws['!merges']) ws['!merges'] = [];
    merges.forEach((item) => {
      ws['!merges'].push(XLSX.utils.decode_range(item));
    });
  }
  if (autoWidth) {
    /*设置worksheet每列的最大宽度*/
    const colWidth = data.map((row) =>
      row.map((val) => {
        /*先判断是否为null/undefined*/
        if (val == null) {
          return {
            wch: 10,
          };
        } else if (val.toString().charCodeAt(0) > 255) {
          /*再判断是否为中文*/
          return {
            wch: val.toString().length * 2,
          };
        } else {
          return {
            wch: val.toString().length,
          };
        }
      }),
    );
    /*以第一行为初始值*/
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
      for (let j = 0; j < colWidth[i].length; j++) {
        if (result[j] && result[j]['wch'] < colWidth[i][j]['wch']) {
          result[j]['wch'] = colWidth[i][j]['wch'];
        }
      }
    }
    ws['!cols'] = result;
  }

  if (Object.values(mengXiData)?.length) {
    Object.values(mengXiData)?.forEach((m) => {
      wb.SheetNames.push(m?.name || ws_name);
      wb.Sheets[m?.name || ws_name] = sheet_from_array_of_arrays(m?.data);
    });
  } else {
    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;
  }

  var wbout = XLSX.write(wb, {
    bookType: bookType,
    bookSST: false,
    type: 'binary',
  });
  saveAs(
    new Blob([s2ab(wbout)], {
      type: 'application/octet-stream',
    }),
    `${filename}.${bookType}`,
  );
}

export function export_json_sheets_to_excel(params) {
  const { list = [], name = '', type = 'xlsx' } = params;
  var wb = new Workbook();
  list?.forEach((item, index) => {
    let {
      multiHeader = [],
      header,
      data,
      merges = [],
      autoWidth = true,
      sheetName = `sheet${index}`,
    } = item;
    data = [...data];
    data.unshift(header);

    for (let i = multiHeader.length - 1; i > -1; i--) {
      data.unshift(multiHeader[i]);
    }
    let ws = sheet_from_array_of_arrays(data);

    if (merges.length > 0) {
      if (!ws['!merges']) ws['!merges'] = [];
      merges.forEach((item) => {
        ws['!merges'].push(XLSX.utils.decode_range(item));
      });
    }

    if (autoWidth) {
      /*设置worksheet每列的最大宽度*/
      const colWidth = data.map((row) =>
        row.map((val) => {
          /*先判断是否为null/undefined*/
          if (val == null) {
            return {
              wch: 10,
            };
          } else if (val.toString().charCodeAt(0) > 255) {
            /*再判断是否为中文*/
            return {
              wch: val.toString().length * 2,
            };
          } else {
            return {
              wch: val.toString().length,
            };
          }
        }),
      );
      /*以第一行为初始值*/
      let result = colWidth[0];
      for (let i = 1; i < colWidth.length; i++) {
        for (let j = 0; j < colWidth[i].length; j++) {
          if (result[j]['wch'] < colWidth[i][j]['wch']) {
            result[j]['wch'] = colWidth[i][j]['wch'];
          }
        }
      }
      ws['!cols'] = result;
    }
    wb.SheetNames.push(sheetName);
    wb.Sheets[sheetName] = ws;
  });
  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary',
  });
  saveAs(
    new Blob([s2ab(wbout)], {
      type: 'application/octet-stream',
    }),
    `${name}.${type}`,
  );
}

/**
 * 树级结构表导出excel
 * @param {Array} treeData 树级数据，必须包含children字段
 * @param {Array} columns 表头，如下：
 * let alignObj = { alignment: { vertical: 'middle', horizontal: 'center' } };
let columns = [
  { header: '', key: 'A', style: alignObj },
  { header: '', key: 'B', style: alignObj },
  { header: '', key: 'C', style: alignObj },
  { header: '', key: 'D', style: alignObj },
];
 * @param {string} fileName 文件名称
 */

export const exportGroup = async (treeData = [], columns = [], fileName = '导出') => {
  function tree2arr(tree, lv = 1) {
    let res = [];
    for (const item of tree) {
      let temp = {};
      const { children, ...i } = item;
      for (const key in i) {
        temp[key] = i[key] || null;
      }
      temp.lv = lv;
      res.push(temp);
      if (children && children.length) {
        const childs = tree2arr(children, lv + 1);
        res = res.concat(childs);
      }
    }
    return res;
  }

  let workbook = new ExcelJS.Workbook();
  let worksheet = workbook.addWorksheet('fileName', { views: [{ showGridLines: true }] });

  const flatArr = tree2arr(treeData);
  worksheet.columns = columns.map((x) => ({
    ...x,
    width:
      Math.max.apply(null, [
        ...flatArr.map((y) => y[x.key]?.length || 0),
        x.header?.length + 2 || 0,
      ]) || 15,
  }));
  flatArr.map((item, idx) => {
    worksheet.addRow(item).commit();
    const row = worksheet.getRow(idx + 2);
    row.outlineLevel = item.lv - 1;
    if (item.lv > 1) {
      row.hidden = true;
    }
  });
  worksheet.properties.outlineProperties = {
    summaryBelow: false,
    summaryRight: false,
  };
  workbook.xlsx.writeBuffer().then(function (buffer) {
    saveAs(new Blob([buffer], { type: 'application/octet-stream' }), `${fileName}.xlsx`);
  });
};

/**
 * 多sheet表格导出excel
 * @param {Array} sheets 多表格数据数组，如下：
 * sheets = [{
      columns:[], // 表头
      title:"", // 表标题
      data:[], // 数据
      myMerges: [], // 需要合拼的单元格数据
      mergeIndex: [4], // 需要合并的列 如果需要单独设置样式
      insertTop:[],// 插入表头上方的额外数据
      ...
   }];
 * @param {string} fileName 文件名称
 */

export const exportMoreSheet = async (sheets, fileName = '导出') => {
  // 多sheet表格导出
  let workbook = new ExcelJS.Workbook();
  sheets.map((item, index) => {
    let sheetName = 'Sheet' + (index + 1);
    let worksheet = workbook.addWorksheet(sheetName, { views: [{ showGridLines: true }] });

    /**columns */
    let columns = [], // 多级表头
      lastColumns = [], //最后一级表头
      mergeCells = {}, // parentName:[startIndex,endIndex]
      startIndex = 1, // 记录表头实际开始位置 用于合并表头
      depth = 0; // 表头深度

    //递归表头深度
    const getArrayDepth = (data, lv) => {
      let beforDepth = 1;
      data.forEach((t) => {
        if (t?.children?.length) {
          let nextDepth = getArrayDepth(t.children) + 1;
          if (nextDepth > beforDepth) {
            beforDepth = nextDepth;
          }
        }
      });
      return beforDepth;
    };
    depth = getArrayDepth(item.columns);
    columns = Array(depth).fill([]);

    //填充表头
    const setColumns = (lv, type, ...arg) => {
      const empty = !columns[lv].length;
      //当前表头未填充 将上一级表头填充至此
      if (lv && empty) {
        columns[lv] = [...columns[lv - 1]];
      }
      if (type) {
        //没有子集 填充lv~lv+n级表头
        columns = columns.map((t, i) => {
          if (i >= lv) {
            return [...t, ...arg];
          }
          return t;
        });
        return;
      }
      columns[lv].push(...arg);
    };

    const deepColumns = (data, lv, parentIndex) => {
      let count = 0; //子集计数
      data.map((t, idx) => {
        if (t?.children) {
          const num = deepColumns(t?.children, lv + 1, `${parentIndex}_${idx}`);
          const length = columns[lv]?.length || 0;
          mergeCells[`${parentIndex}_${idx}`] = [lv, length + 1, lv, length + num]; //有子集 横向合并

          const repeatItem = Array(num).fill(t.header);
          setColumns(lv, 0, ...repeatItem);
          count += num;
        } else {
          setColumns(lv, 1, t.header);
          count++;
          lastColumns.push(t);
          const length = columns[lv]?.length || 0;
          mergeCells[`${parentIndex}_${idx}`] = [lv, length, depth - 1, length]; //没有子集 纵向合并
        }
      });
      return count;
    };

    deepColumns(item.columns, 0, 0);
    worksheet.columns = lastColumns;
    const column_cell = worksheet.getRow(1);
    column_cell.alignment = item?.columnsStyle?.alignment || {
      horizontal: 'center',
      vertical: 'middle',
    };
    column_cell.font = item?.columnsStyle?.font || {
      size: 12,
      bold: true,
    };

    /**data */
    item.data.map((item1, idx) => {
      worksheet.addRow(item1).commit();
      item?.mergeIndex?.map((mergeIndex) => {
        const cells = worksheet.getCell(idx + 2, mergeIndex);
        cells.alignment = item?.mergeStyle?.alignment || {
          horizontal: 'center',
          vertical: 'middle',
        };
      });
    });

    //父级表头
    if (columns.length > 1) {
      columns.forEach((t, i) => {
        if (i === columns.length - 1) return;
        worksheet.spliceRows(i + 1, 0, t);
        const column_cell = worksheet.getRow(i + 1);
        column_cell.alignment = item?.columnsStyle?.alignment || {
          horizontal: 'center',
          vertical: 'middle',
        };
        column_cell.font = item?.columnsStyle?.font || {
          size: 12,
          bold: true,
        };
      });
    }

    /**insertTop */
    if (!!item?.insertTop) {
      item?.insertTop.map((t, i) => {
        worksheet.spliceRows(1 + i, 0, t);
        const columns_row = worksheet.getRow(1);
        startIndex++;
        columns_row.font = item?.columnsStyle?.font || {
          size: 12,
          bold: true,
        };
      });
    }

    /**title */
    if (!!item?.title) {
      startIndex++;
      worksheet.spliceRows(1, 0, [item.title]);
      worksheet.mergeCells(1, 1, 1, lastColumns.length);
      const titleRow = worksheet.getRow(1);
      // 高度
      titleRow.height = item?.headerStyle?.height || 20;
      // 字体设置
      titleRow.font = item?.headerStyle?.font || {
        size: 16,
        bold: false,
      };
      // 对齐方式
      titleRow.alignment = item?.headerStyle?.alignment || {
        horizontal: 'center',
        vertical: 'middle',
      };
    }

    worksheet.properties.outlineProperties = {
      summaryBelow: false,
      summaryRight: false,
    };

    /**合并单元格 */
    item?.myMerges?.map((x) => {
      worksheet.mergeCells(x[0], x[1], x[2], x[3]);
    });
    Object.values(mergeCells).map((t) => {
      //合并父级表头
      worksheet.mergeCells(t[0] + startIndex, t[1], t[2] + startIndex, t[3]);
    });
  });
  workbook.xlsx.writeBuffer().then(function (buffer) {
    saveAs(new Blob([buffer], { type: 'application/octet-stream' }), `${fileName}.xlsx`);
  });
};
